package vn.edu.hut.soict.translate.database.tool;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import vn.edu.hut.soict.alignment.AlignmentReverser;
import vn.edu.hut.soict.translate.database.TranslatorDatabase;
import vn.edu.hut.soict.translate.utils.StringUtils;

public class ReverseDatabase {
	private static String EV_ALIGNMENT = "res/corpus/EV_align.txt";
	private static String EV_SOURCE = "res/corpus/EV_matched.txt";

	private TranslatorDatabase database;
	BufferedReader alignmentFile, matchedFile;

	public ReverseDatabase() {
		database = new TranslatorDatabase();
		alignmentFile = null;
		matchedFile = null;
		try {
			alignmentFile = new BufferedReader(new InputStreamReader(new FileInputStream(EV_ALIGNMENT), "utf-8"));
			matchedFile = new BufferedReader(new InputStreamReader(new FileInputStream(EV_SOURCE), "utf-8"));
		}
		catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addAllSentencesToDatabase() {
		int i = 0;
		database.connect();
		System.out.println("Start adding sentences to database...");
		for (;;) {
			i++;
			try {
				String english = StringUtils.addExtraSpace(matchedFile.readLine());
				String vietnamese = StringUtils.addExtraSpace(matchedFile.readLine());
				String alignment = alignmentFile.readLine();
				if (english == null || vietnamese == null || alignment == null) {
					break;
				}
				AlignmentReverser reverser = new AlignmentReverser(english, alignment);
				database.insertRowToBilingual(reverser.destination(), english, reverser.reversedAlignment());
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i % 1000 == 0) {
				System.out.println(i);
			}
		}
		database.disconnect();
		System.out.println("Finish!");
	}

	public static void main(String[] args) {
		ReverseDatabase reverseDatabase = new ReverseDatabase();
		reverseDatabase.addAllSentencesToDatabase();
	}

}
